package club.caihappy.store.service.impl;

import club.caihappy.store.entity.User;
import club.caihappy.store.mapper.UserMapper;
import club.caihappy.store.service.IUserService;
import club.caihappy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * 用户模块业务层的实现类
 * Created by DELL on 2022/2/27
 **/
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        String username = user.getUsername();
        User byUserName = userMapper.findByUserName(username);
        //判断用户名是否被占用
        if (byUserName != null) {
            throw new UsernameDuplicatedException("用户名已被占用");
        }

        String oldPassword = user.getPassword();
        //获取盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将密码和盐值作为一个整体加密处理
        String md5Password = getMD5Password(salt, oldPassword);
        user.setPassword(md5Password);
        //将盐值存入数据库
        user.setSalt(salt);

        //补全数据idDelete(0表示存在，1表示删除)和日志
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        //如果用户名未被占用，执行注册操作(insert 返回值为1时表示注册成功)
        Integer insert = userMapper.insert(user);
        if (insert != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据用户名查询用户是否存在，如果不存在抛出异常
        User byUserName = userMapper.findByUserName(username);
        if (byUserName == null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //检测用户的密码是否匹配
        String md5Password = getMD5Password(byUserName.getSalt(), password);
        if (!md5Password.equals(byUserName.getPassword())) {
            throw new PasswordNotMatchException("用户名或密码错误");
        }

        //判断is_delete字段的值是否为1，为1表示被标记为删除
        if (byUserName.getIsDelete() != 0) {
            throw new UserNotFoundException("用户数据不存在");
        }

        //包装返回给浏览器的用户信息,提升了系统的性能
        User user = new User();
        user.setUid(byUserName.getUid());
        user.setUsername(byUserName.getUsername());
        user.setAvatar(byUserName.getAvatar());

        return user;
    }

    /**
     * 修改密码
     *
     * @param uid         通过uid判断是否存在
     * @param username    修改人
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findUserByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //原始密码和数据库密码进行比较
        String md5Password = getMD5Password(result.getSalt(), oldPassword);
        if (!md5Password.equals(result.getPassword())) {
            throw new PasswordNotMatchException("用户名或密码错误");
        }
        //将新的密码设置到数据库,将新的密码进行加密
        String resPassword = getMD5Password(result.getSalt(), newPassword);
        Integer rows = userMapper.updatePasswordByUid(uid, resPassword, username, new Date());
        if (rows != 1) {
            throw new UpdateException("更新数据产生未知异常");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User result = isUserExist(uid);
        User user = new User();
        user.setUsername(result.getUsername());
        user.setEmail(result.getEmail());
        user.setPhone(result.getPhone());
        user.setGender(result.getGender());
        return user;
    }

    @Override
    public void changeInfo(Integer uid, String username, User user) {
        isUserExist(uid);
        user.setUid(uid);
//        user.setUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());

        Integer row = userMapper.updateInfoByUid(user);
        if (row != 1) {
            throw new UpdateException("更新用户数据时发生未知异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String modifiedUser) {
        isUserExist(uid);
        Integer row = userMapper.updateAvatarByUid(uid, avatar, modifiedUser, new Date());
        if (row != 1) {
            throw new UpdateException("更新用户头像时发生未知异常");
        }
    }

    /*判断用户是否存在并返回用户对象*/
    private User isUserExist(Integer uid) {
        User result = userMapper.findUserByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        return result;
    }

    /*定义一个md5算法的加密处理*/
    private String getMD5Password(String salt, String password) {
        for (int i = 0; i < 3; i++) {
            //md5加密算法3次加密
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        //返回加密后的密码
        return password;
    }
}
